package com.experiment.experiment_big.controller;


import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.experiment.experiment_big.entity.DangerRegion;
import com.experiment.experiment_big.service.DangerRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Wrapper;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-06-13
 */
@Controller
public class DangerRegionController {
    @Autowired
    private DangerRegionService dangerRegionService;

    /**
     * 获得所有的高危地区，并返回页面
     * @param model
     * @param excel //判断是否为导出excel请求
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/high_risk")
    public String high_risk(Model model, String excel, HttpServletResponse response) throws IOException {
        List<DangerRegion> list = dangerRegionService.list(null);
        model.addAttribute("list",list);
        if(excel!=null){
            ServletOutputStream out = out = response.getOutputStream();
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            String filename = "高危地区";
            writer.write(list,new WriteSheet());
            //通知浏览器以附件的形式下载处理，设置返回头要注意文件名有中文
            response.setHeader("Content-disposition", "attachment;filename=" + new String( filename.getBytes("gb2312"), "ISO8859-1" ) + ".xlsx");
            writer.finish();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            out.flush();
        }
        return "high_risk";
    }

    /**
     * 删除高危地区
     * @param id
     * @return
     */
    @RequestMapping("/deleteDangerRegion")
    public String deleteDangerRegion(String id){

        boolean fate = dangerRegionService.removeById(Integer.valueOf(id));
        return "redirect:/high_risk";
    }

    /**
     * 增加高危地区
     * @param dangerRegion
     * @return
     */
    @RequestMapping("/addDangerRegion")
    public String addDangerRegion(DangerRegion dangerRegion){
        boolean fate = dangerRegionService.save(dangerRegion);
        return "redirect:/high_risk";
    }

}

